"""
旅游助手Agent主入口文件
提供命令行接口和API服务
"""

import os
import sys
import argparse
import logging
from typing import Optional, Dict, Any
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))

from src.agent.agent_factory import AgentFactory
from src.models.llm_config import LLMConfig
from src.utils.logger import setup_logger


class TravelAgentApp:
    """旅游助手应用主类"""
    
    def __init__(self):
        """初始化应用"""
        self.logger = setup_logger(__name__)
        self.factory = AgentFactory()
        self.system = None
        
        self.logger.info("旅游助手应用初始化完成")
    
    def initialize_system(self, config: Optional[LLMConfig] = None) -> bool:
        """
        初始化系统
        
        Args:
            config: LLM配置
            
        Returns:
            初始化是否成功
        """
        try:
            self.logger.info("开始初始化系统")
            
            # 创建完整系统
            self.system = self.factory.create_complete_system(config)
            
            # 测试系统
            test_results = self.factory.test_system(self.system)
            
            if test_results.get("agent_test") and test_results.get("workflow_test"):
                self.logger.info("系统初始化成功")
                return True
            else:
                self.logger.error(f"系统初始化失败: {test_results}")
                return False
                
        except Exception as e:
            self.logger.error(f"系统初始化失败: {e}")
            return False
    
    def chat(self, query: str, thread_id: str = "default") -> Dict[str, Any]:
        """
        处理用户查询
        
        Args:
            query: 用户查询
            thread_id: 对话线程ID
            
        Returns:
            处理结果
        """
        try:
            if not self.system:
                return {
                    "error": "系统未初始化",
                    "content": "请先初始化系统"
                }
            
            self.logger.info(f"处理查询: {query}")
            
            # 使用工作流处理查询
            workflow = self.system["workflow"]
            result = workflow.process_query(query, thread_id)
            
            # 提取响应内容
            messages = result.get("messages", [])
            if messages:
                last_message = messages[-1]
                content = last_message.get("content", "抱歉，无法生成响应")
            else:
                content = "抱歉，无法生成响应"
            
            return {
                "content": content,
                "intent": result.get("intent", "unknown"),
                "tool_used": result.get("tool_used", ""),
                "quality_score": result.get("quality_score", 0.0),
                "needs_clarification": result.get("needs_clarification", False),
                "conversation_history": messages
            }
            
        except Exception as e:
            self.logger.error(f"处理查询失败: {e}")
            return {
                "error": str(e),
                "content": f"处理查询时出现错误: {str(e)}"
            }
    
    def get_conversation_history(self, thread_id: str = "default") -> list:
        """获取对话历史"""
        try:
            if not self.system:
                return []
            
            workflow = self.system["workflow"]
            return workflow.get_conversation_history(thread_id)
            
        except Exception as e:
            self.logger.error(f"获取对话历史失败: {e}")
            return []
    
    def reset_conversation(self, thread_id: str = "default"):
        """重置对话"""
        try:
            if not self.system:
                return
            
            workflow = self.system["workflow"]
            workflow.reset_conversation(thread_id)
            
        except Exception as e:
            self.logger.error(f"重置对话失败: {e}")
    
    def get_system_status(self) -> Dict[str, Any]:
        """获取系统状态"""
        try:
            if not self.system:
                return {"status": "not_initialized"}
            
            return self.factory.get_system_status(self.system)
            
        except Exception as e:
            self.logger.error(f"获取系统状态失败: {e}")
            return {"error": str(e)}


def main():
    """主函数"""
    parser = argparse.ArgumentParser(description="旅游助手Agent")
    parser.add_argument("--mode", choices=["cli", "api"], default="cli", help="运行模式")
    parser.add_argument("--port", type=int, default=8000, help="API服务端口")
    parser.add_argument("--host", default="0.0.0.0", help="API服务主机")
    parser.add_argument("--config", help="配置文件路径")
    
    args = parser.parse_args()
    
    # 设置日志
    setup_logger("travel_agent", level="INFO")
    
    # 创建应用
    app = TravelAgentApp()
    
    # 初始化系统
    try:
        config = LLMConfig() if not args.config else None
        if not app.initialize_system(config):
            print("系统初始化失败，请检查配置")
            sys.exit(1)
    except Exception as e:
        print(f"系统初始化失败: {e}")
        sys.exit(1)
    
    if args.mode == "cli":
        # 命令行模式
        run_cli_mode(app)
    elif args.mode == "api":
        # API模式
        run_api_mode(app, args.host, args.port)


def run_cli_mode(app: TravelAgentApp):
    """运行命令行模式"""
    print("=== 旅游助手Agent ===")
    print("输入 'quit' 或 'exit' 退出")
    print("输入 'status' 查看系统状态")
    print("输入 'reset' 重置对话")
    print("=" * 30)
    
    thread_id = "cli_session"
    
    while True:
        try:
            query = input("\n您: ").strip()
            
            if query.lower() in ['quit', 'exit', '退出']:
                print("再见！")
                break
            elif query.lower() == 'status':
                status = app.get_system_status()
                print(f"系统状态: {status}")
                continue
            elif query.lower() == 'reset':
                app.reset_conversation(thread_id)
                print("对话已重置")
                continue
            elif not query:
                continue
            
            # 处理查询
            result = app.chat(query, thread_id)
            
            if "error" in result:
                print(f"错误: {result['error']}")
            else:
                print(f"\n助手: {result['content']}")
                
                # 显示额外信息
                if result.get("needs_clarification"):
                    print("(需要更多信息)")
                
                if result.get("quality_score", 0) > 0:
                    print(f"(质量得分: {result['quality_score']:.2f})")
        
        except KeyboardInterrupt:
            print("\n\n再见！")
            break
        except Exception as e:
            print(f"处理查询时出现错误: {e}")


def run_api_mode(app: TravelAgentApp, host: str, port: int):
    """运行API模式"""
    try:
        from flask import Flask, request, jsonify
        
        # 创建Flask应用
        flask_app = Flask(__name__)
        
        @flask_app.route('/chat', methods=['POST'])
        def chat():
            """聊天接口"""
            try:
                data = request.get_json()
                query = data.get('query', '')
                thread_id = data.get('thread_id', 'default')
                
                if not query:
                    return jsonify({"error": "查询不能为空"}), 400
                
                result = app.chat(query, thread_id)
                return jsonify(result)
                
            except Exception as e:
                return jsonify({"error": str(e)}), 500
        
        @flask_app.route('/history/<thread_id>', methods=['GET'])
        def get_history(thread_id):
            """获取对话历史"""
            try:
                history = app.get_conversation_history(thread_id)
                return jsonify({"history": history})
            except Exception as e:
                return jsonify({"error": str(e)}), 500
        
        @flask_app.route('/reset/<thread_id>', methods=['POST'])
        def reset_conversation(thread_id):
            """重置对话"""
            try:
                app.reset_conversation(thread_id)
                return jsonify({"message": "对话已重置"})
            except Exception as e:
                return jsonify({"error": str(e)}), 500
        
        @flask_app.route('/status', methods=['GET'])
        def get_status():
            """获取系统状态"""
            try:
                status = app.get_system_status()
                return jsonify(status)
            except Exception as e:
                return jsonify({"error": str(e)}), 500
        
        @flask_app.route('/health', methods=['GET'])
        def health_check():
            """健康检查"""
            return jsonify({"status": "healthy"})
        
        print(f"启动API服务: http://{host}:{port}")
        flask_app.run(host=host, port=port, debug=False)
        
    except ImportError:
        print("API模式需要安装Flask: pip install flask")
        sys.exit(1)
    except Exception as e:
        print(f"启动API服务失败: {e}")
        sys.exit(1)


if __name__ == "__main__":
    main()
